package com.dqyt.app.service;


import com.alibaba.fastjson.JSON;
import com.dqyt.app.bean.CylindersReport;
import com.dqyt.app.bean.Report;
import com.dqyt.app.bean.Sample;
import com.dqyt.app.mongo.ReportDao;
import com.dqyt.app.mongo.SampleDao;
import com.dqyt.common.constant.Opt;
import com.dqyt.common.utils.BHUtil;
import com.dqyt.common.utils.StringUtil;
import com.dqyt.common.utils.UserInfoUtil;
import com.dqyt.khjc.bean.BaseBean;
import com.dqyt.khjc.bean.HistoryBean;
import com.dqyt.khjc.bean.ResultMsg;
import com.dqyt.khjc.bean.User;
import com.dqyt.khjc.config.Config;
import com.dqyt.khjc.mapper.HistoryMapper;
import com.dqyt.khjc.swicth.SwitchConfig;
import com.dqyt.khjc.utils.IpUtil;
import com.dqyt.khjc.utils.TimeUtil;
import com.dqyt.quart.AddSimpleJobReq;
import com.dqyt.quart.DeleteJobReq;
import com.dqyt.quart.QuartzManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 报告service
 */
@Service
public class ReportService {

    @Autowired
    private ReportDao mReportDao;

    @Autowired
    private SampleDao mSampleDao;


    @Autowired
    private HistoryMapper historyMapper;

    @Autowired
    private QuartzManager quartzManager;



    public ResultMsg testReport() {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值

        Report report = new Report();
        report.bh = "TEST";
        report.type = Report.BG_TYPE_FHQP;
        report.cylinders = new CylindersReport();
        report.cylinders.bh =  report.bh;
        report.cylinders.wtf = "测试001";

        long time = TimeUtil.getCurrentTimeMillis();
        report.setAddTime(time);
        report.setUpdateTime(time);


        mReportDao.save(report);


        ret.setCode(ResultMsg.SUCESS);
        ret.setMsg("保存成功！");
        return ret;

    }

    /**
     *  分页查询报告
     * @param request
     * @param userId  用户id
     * @param token
     * @param addTime
     * @param reportStatue  报告状态
     * @param bsbh  标识编号
     * @param erweima  二维码
     * @param deviceType  设备类型
     * @param reportProgress  报告进度
     * @return
     */
    public ResultMsg getReportInfos(HttpServletRequest request,Integer page,Integer size, long userId, String token, long addTime, int reportStatue, String bsbh, String erweima,int deviceType,int reportProgress,long wtfId) {

        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {

            // 简单的数据检查
            if (addTime == 0) {
                ret.setCode(ResultMsg.FAIL);
                ret.setMsg("数据错误！");
                return ret;
            }

            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            if (null != ret) {
                return ret;
            }
            if (page != null && size != null) {
                page = (page - 1) * size;
            }
            ret = new ResultMsg();
            // 取得条件数据
            List<Report> Reports = mReportDao.getReportInfos(page,size,addTime, reportStatue, bsbh, erweima,deviceType,reportProgress,wtfId);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(JSON.toJSONString(Reports));
            return ret;
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 新增报告信息
     *
     * @param request
     * @param userId
     * @param token
     * @param json
     * @return
     */
    public ResultMsg addReport(HttpServletRequest request, long userId, String token, String json) {

        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {

            // 简单的数据检查
            if (json == null || "".equals(json)) {
                ret.setCode(ResultMsg.FAIL);
                ret.setMsg("数据错误！");
                return ret;
            }

            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            if (null != ret) {
                return ret;
            }
            ret = new ResultMsg();

            Report Report = JSON.parseObject(json, Report.class);
            // 数据检查
            if (StringUtil.isEmpty(Report.bh) || StringUtil.isEmpty(Report.erweima)) {
                ret.setCode(ResultMsg.FAIL);
                ret.setMsg("数据错误！");
                return ret;
            }
            // 设置一次数据编号
            Report.bh = BHUtil.getBHID(Report.type, Report.bh);

            // 保存数据
            // 取得是否存在旧的数据
            Report oldData = mReportDao.getReportByBH(Report.bh);
            // TODO

            long time = TimeUtil.getCurrentTimeMillis();
            Report.setAddUser(userId + "");
            Report.setAddTime(time);
            Report.setUpdateUser(userId + "");
            Report.setUpdateTime(time);
            Report.setSysStatus(BaseBean.SYS_STATUS_OK);

            mReportDao.save(Report);

            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("录入数据成功");

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 更新报告信息
     *
     * @param request
     * @param userId
     * @param token
     * @param json
     * @return
     */
    public ResultMsg updateReport(HttpServletRequest request, long userId, String token, String json) {

        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {

            // 简单的数据检查
            if (json == null || "".equals(json)) {
                ret.setCode(ResultMsg.FAIL);
                ret.setMsg("数据错误！");
                return ret;
            }

            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            if (null != ret) {
                return ret;
            }
            ret = new ResultMsg();

            Report Report = JSON.parseObject(json, Report.class);
            // 数据检查
            if (StringUtil.isEmpty(Report.bh) || StringUtil.isEmpty(Report.bh) || StringUtil.isEmpty(Report.erweima)) {
                ret.setCode(ResultMsg.FAIL);
                ret.setMsg("数据错误！");
                return ret;
            }

            // 保存数据
            Report oldData = mReportDao.getReportByBH(Report.bh);
            if (oldData == null) {
                ret.setCode(ResultMsg.FAIL);
                ret.setMsg("数据错误！");
                return ret;
            }
//            if (oldData.getUpdateTime() > Report.getUpdateTime()) {
//                ret.setCode(ResultMsg.FAIL);
//                ret.setMsg("该数据已经被其他人更新了！");
//                return ret;
//            }

            long time = TimeUtil.getCurrentTimeMillis();
            Report.setUpdateUser(userId + "");
            Report.setUpdateTime(time);
            Report.setSysStatus(BaseBean.SYS_STATUS_OK);

            mReportDao.save(Report);

            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("更新数据成功");
            ret.setData(JSON.toJSONString(Report));

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 驳回报告
     * @param request
     * @param userId
     * @param token
     * @param bh
     * @param reportProgress
     * @param bhgyy
     * @return
     */
    public ResultMsg  rejectReportDal(HttpServletRequest request, long userId, String token, String bh, int reportProgress, String bhgyy){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            if (null != ret) {
                return ret;
            }
            ret = new ResultMsg();
            User user = UserInfoUtil.getUserInfologin(userId, token);
            if(null == user){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("登录过期");
                return  ret;
            }

            //先查询老的报告
            Report report = mReportDao.getReportByBH(bh);
            report.reportProgress = reportProgress;
            //任何情况被驳回都要清除  审核员和 批准员

            //如果是呼吸器 报告
            if(report.type == Report.BG_TYPE_HXQ){
                //设置核验员的id为自己的id
                report.respirator.pzrId = "";
                report.respirator.pzr = "";
                report.respirator.hyyId = "";
                report.respirator.hyy = "";
            }else if(report.type == Report.BG_TYPE_FHQP){  //如果是复合气瓶的报告
                //设置核验员的id为自己的id
                report.cylinders.pzrId = "";
                report.cylinders.pzr = "";
                report.cylinders.hyyId = "";
                report.cylinders.hyy = "";

            }else if(report.type == Report.BG_TYPE_YLB){  //如果是压力表的报告
                //设置核验员的id为自己的id
                report.pressure.pzrId = "";
                report.pressure.pzr = "";
                report.pressure.hyyId = "";
                report.pressure.hyy = "";
            }
            //不合格原因
            report.bhgyy = bhgyy;
            long time = TimeUtil.getCurrentTimeMillis();
            report.setUpdateUser(user.getUserId() + "");
            report.setUpdateTime(time);
            mReportDao.save(report);
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("成功");

            //
            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添维修记录
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "] 驳回了标识编号为： [" + report.bsbh + "]的报告 ");
                historyBean.setType(Opt.BGGL_BHBG);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(report.bsbh));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }




        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 报告通过审核
     *
     * @param request
     * @param bh
     * @return
     */
    public ResultMsg reportAdoptExamine(HttpServletRequest request,long userId, String token, String bh) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            if (null != ret) {
                return ret;
            }
            ret = new ResultMsg();
            User user = UserInfoUtil.getUserInfologin(userId, token);
            if (null == user) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("登录过期");
                return ret;
            }

            if(0 == user.getSealId()){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("你还没有电子签章");
                return ret;
            }

            //先查询老的报告
            Report report = mReportDao.getReportByBH(bh);
            //设报告的进度为待审批
            report.reportProgress = 3;
            //如果是呼吸器 报告
            if(report.type == Report.BG_TYPE_HXQ){
                //设置核验员的id为自己的id
                report.respirator.hyyId = String.valueOf(user.getUserId());
                report.respirator.hyy = user.getUserName();
            }else if(report.type == Report.BG_TYPE_FHQP){  //如果是复合气瓶的报告
                //设置核验员的id为自己的id
                report.cylinders.hyyId = String.valueOf(user.getUserId());
                report.cylinders.hyy = user.getUserName();
            }else if(report.type == Report.BG_TYPE_YLB){  //如果是压力表的报告
                //设置核验员的id为自己的id
                report.pressure.hyyId = String.valueOf(user.getUserId());
                report.pressure.hyy = user.getUserName();
            }
            long time = TimeUtil.getCurrentTimeMillis();
            report.setUpdateUser(user.getUserId() + "");
            report.setUpdateTime(time);
            mReportDao.save(report);
            ret.setCode(ResultMsg.SUCESS);


            DeleteJobReq deleteJobReq = new DeleteJobReq();
            deleteJobReq.setJobName(Config.PZBG_TASK);
            deleteJobReq.setJobGroupName(Config.PZBG_TASK_GROUP);
            deleteJobReq.setTriggerName(Config.PZBG_TASK);
            deleteJobReq.setTriggerGroupName(Config.PZBG_TASK_GROUP);
            quartzManager.removeJob(deleteJobReq);


            Calendar beforeTime = Calendar.getInstance();
            // 5 秒之后的时间
            beforeTime.add(Calendar.SECOND, Config.MINUTE_5);
            Date beforeDate = beforeTime.getTime();
            AddSimpleJobReq addSimpleJobReq = new AddSimpleJobReq();
            addSimpleJobReq.setDate(beforeDate);
            addSimpleJobReq.setJobClass("PzrwTask");
            quartzManager.addSimpleJob(addSimpleJobReq, Config.PZBG_TASK,Config.PZBG_TASK_GROUP);

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添维修记录
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "] 通过了标识编号为： [" + report.bsbh + "]的待核验报告 ");
                historyBean.setType(Opt.BGGL_DHYBG_TGPZ);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(report.bsbh));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }




        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 报告通过 批准
     *
     * @param request
     * @param bh
     * @return
     */
    public ResultMsg reportAdoptApproval(HttpServletRequest request,long userId, String token, String bh) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            if (null != ret) {
                return ret;
            }
            ret = new ResultMsg();
            User user = UserInfoUtil.getUserInfologin(userId, token);
            if (null == user) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("登录过期");
                return ret;
            }

            if(0 == user.getSealId()){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("你还没有电子签章");
                return ret;
            }

            //先查询老的报告
            Report report = mReportDao.getReportByBH(bh);
            //设报告的进度为 已完成
            report.reportProgress = 4;
            //如果是呼吸器 报告
            if(report.type == Report.BG_TYPE_HXQ){
                //设置核验员的id为自己的id
                report.respirator.pzrId = String.valueOf(user.getUserId());
                report.respirator.pzr = user.getUserName();
            }else if(report.type == Report.BG_TYPE_FHQP){  //如果是复合气瓶的报告
                //设置核验员的id为自己的id
                report.cylinders.pzrId = String.valueOf(user.getUserId());
                report.cylinders.pzr = user.getUserName();
            }else if(report.type == Report.BG_TYPE_YLB){  //如果是压力表的报告
                //设置核验员的id为自己的id
                report.pressure.pzrId = String.valueOf(user.getUserId());
                report.pressure.pzr = user.getUserName();
            }

            //如果是气瓶或者是面罩  就修改样品信息中的状态
            if(report.type == Report.BG_TYPE_FHQP || report.type == Report.BG_TYPE_HXQ){
                //报告最终批准之后  设置样品的状态
                List<Sample> list =  mSampleDao.getSample(0, report.sbbh, report.bsbh, "");
                if(list.size()>0){
                    Sample  sample22 = list.get(0);
                    switch (report.reportStatue){
                        case 1:   //合格
                            sample22.sampleStatue =4;
                            break;
                        case 2:  // 不合格
                            sample22.sampleStatue =3;
                            break;
                    }
                    //如果是不合格就设置样品里面不合格原因
                    if(sample22.sampleStatue ==3){
                        if(sample22.type == Sample.YP_TYPE_HXQ){
                            switch (report.failedStart){
                                case 1:
                                    sample22.bhgyy=report.respirator.nr_bz;
                                    break;
                                case 2:
                                    sample22.bhgyy=report.respirator.nr_bz;
                                    break;
                                case 3:
                                    sample22.bhgyy="压力表不合格";
                                    break;
                                default:
                                    sample22.bhgyy="";
                                    break;
                            }
                        }else if(sample22.type == Sample.YP_TYPE_FHQP){
                            switch (report.failedStart){
                                case 1:
                                    sample22.bhgyy="气瓶合格瓶阀不合格";
                                    break;
                                case 2: //如果是报废就填写报废原因
                                    sample22.bhgyy="报废原因："+report.cylinders.jl;
                                    break;
                                default:
                                    sample22.bhgyy="";
                                    break;
                            }
                        }
                    }
                    if(sample22.type == Sample.YP_TYPE_HXQ){
                        sample22.respirator.zsjyrq = report.respirator.jyrq;
                    }else{
                        sample22.cylinders.zsjyrq = report.cylinders.jyrq;
                    }
                    mSampleDao.save(sample22);
                }
            }


            long time = TimeUtil.getCurrentTimeMillis();
            report.setUpdateUser(user.getUserId() + "");
            report.setUpdateTime(time);
            mReportDao.save(report);
            ret.setCode(ResultMsg.SUCESS);


            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添维修记录
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "] 通过了标识编号为： [" + report.bsbh + "]的待批准报告 ");
                historyBean.setType(Opt.BGGL_DPZBG_TGPZ);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(report.bsbh));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




}
